package com.arpa.oms.controller;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.oms.domain.dto.PurchaseDto;
import com.arpa.oms.domain.dto.PurchaseItemDto;
import com.arpa.oms.domain.entity.Purchase;
import com.arpa.oms.domain.enums.OrderStatusEnum;
import com.arpa.oms.domain.vo.OmsSaleReturnVO;
import com.arpa.oms.domain.vo.PurchaseItemVO;
import com.arpa.oms.domain.vo.PurchaseVo;
import com.arpa.oms.service.IPurchaseService;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * OMS采购单 Controller
 * </p>
 *
 * @author LEO
 * @since 2020-10-23
 */
@Api(tags = "OMS采购单")
@RestController
@RequestMapping(value = "/oms/purchase", produces = "application/json;charset=UTF-8")
@Log4j2(topic = "business")
public class PurchaseController {

    private final IPurchaseService purchaseService;

    public PurchaseController(IPurchaseService purchaseService) {
        this.purchaseService = purchaseService;
    }

    /**
     * OMS采购单列表
     *
     * @param dto
     * @param request
     * @return
     */
    @ApiOperation(value = "OMS采购单列表", notes = "OMS采购单列表接口、采购单审核列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "gmtCreatedStart", value = "创建日期起", paramType = "query", dataType = "string", defaultValue = ""),
            @ApiImplicitParam(name = "gmtCreatedEnd", value = "创建日期止", paramType = "query", dataType = "string", defaultValue = ""),
            @ApiImplicitParam(name = "gmtModifiedStart", value = "修改日期起", paramType = "query", dataType = "string", defaultValue = ""),
            @ApiImplicitParam(name = "gmtModifiedEnd", value = "修改日期止", paramType = "query", dataType = "string", defaultValue = ""),
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = PurchaseVo.class))
    @NeedLogin
    @GetMapping()
    public Result list(PurchaseDto dto, HttpServletRequest request) {
        try {

            dto.setGroupCode(UserUtil.getBranchCode());
            dto.setShipmentCode(UserUtil.getLoginWarehouseCodeOrShipmentCode());
            dto.setWarehouseCodes(UserUtil.getShipmentAuthorizeWarehouseCodes());

            PurchaseVo purchaseVo = purchaseService.queryListSum(dto);
            List<PurchaseVo> purchaseVos = purchaseService.queryList(dto);

            Page returnPage = new Page(dto.getPageNum(), dto.getPageSize());
            returnPage.setRecords(purchaseVos);
            returnPage.setTotal(purchaseVo.getTotal());
            returnPage.setSumObject(purchaseVo);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 保存采购单warehouseCode
     *
     * @param purchase 采购单
     * @param request
     * @return
     */
    @ApiOperation(value = "创建采购单 ", notes = "创建采购单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
    })
    @NeedLogin
    @PostMapping()
    public Result save(@RequestBody @Valid Purchase purchase, HttpServletRequest request) {
        try {
            if (IterUtil.isEmpty(purchase.getPurchaseItemList())) {
                return Result.error("新增采购单失败，采购商品为空！");
            }
            purchase.setShipmentCode(UserUtil.getShipmentCompanyCode());
            purchase.setShipmentName(UserUtil.getShipmentCompanyName());
            purchase.setStatus(OrderStatusEnum.NEWS);
            purchaseService.create(purchase);
            return Result.ok("保存成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 提交采购单
     *
     * @param entity  采购单
     * @param request
     * @return
     */
    @ApiOperation(value = "提交采购单 ", notes = "提交采购单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String",
                    defaultValue = "Bearer 123456"),
    })
    @NeedLogin
    @PostMapping("/submit")
    public Result submit(@RequestBody @Valid Purchase entity, HttpServletRequest request) {
        try {
            if (IterUtil.isEmpty(entity.getPurchaseItemList())) {
                return Result.error("新增采购单失败，采购商品为空！");
            }
            entity.setShipmentCode(UserUtil.getShipmentCompanyCode());
            entity.setShipmentName(UserUtil.getShipmentCompanyName());
            purchaseService.submit(entity);
            return Result.ok("提交成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 采购单详情
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "采购单详情", notes = "采购单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "code", value = "采购单号", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = PurchaseVo.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result receive(@PathVariable String code, HttpServletRequest request) {
        try {
            PurchaseVo purchaseVo = purchaseService.getByCode(code.trim());
            return Result.ok().data(purchaseVo);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 作废采购单
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "作废采购单", notes = "作废采购单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "code", value = "采购单号", paramType = "path", dataType = "String")
    })
    @NeedLogin
    @GetMapping(value = "/annul/{code}")
    public Result annul(@PathVariable String code, HttpServletRequest request) {
        try {
            purchaseService.annul(code);
            return Result.ok("作废成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 采购单审核
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "采购单审核", notes = "采购单审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "code", value = "采购单号", paramType = "path", dataType = "String", required = true),
            @ApiImplicitParam(name = "status", value = "审核结果：PASS/NO_PASS 大写", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "verifyOpinion", value = "审核意见", paramType = "query", dataType = "String"),
    })
    @NeedLogin
    @GetMapping(value = "/verify/{code}")
    public Result verify(@PathVariable String code, String status, @RequestParam(required = false) String verifyOpinion, HttpServletRequest request) {
        try {

            purchaseService.verify(code, status, verifyOpinion);
            return Result.ok("审核成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 获取 OMS采购单 审核列表
     *
     * @param dto
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 OMS采购单 审核列表", notes = "获取 OMS采购单 审核列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = OmsSaleReturnVO.class))
    @NeedLogin
    @GetMapping("/auditList")
    public Result auditList(PurchaseDto dto, HttpServletRequest request) {
        try {
            dto.setGroupCode(UserUtil.getBranchCode());
            dto.setShipmentCode(UserUtil.getLoginWarehouseCodeOrShipmentCode());
            dto.setWarehouseCodes(UserUtil.getShipmentAuthorizeWarehouseCodes());
            if (StrUtil.isBlank(dto.getAuditStatus())) {
                List<String> auditStatus = Arrays.asList(OrderStatusEnum.PENDING.getValue(), OrderStatusEnum.NO_PASS.getValue(), OrderStatusEnum.PASS.getValue());
                String auditStatusStr = auditStatus.stream().map(c -> StrUtil.wrap(c, "'")).collect(Collectors.joining(","));
                dto.setAuditStatus(auditStatusStr);
            }

            PurchaseVo purchaseVo = purchaseService.queryListSum(dto);
            purchaseVo.setGroupCode(UserUtil.getBranchCode());
            List<PurchaseVo> purchaseVos = purchaseService.queryList(dto);

            Page returnPage = new Page(dto.getPageNum(), dto.getPageSize());
            returnPage.setRecords(purchaseVos);
            returnPage.setTotal(purchaseVo.getTotal());
            returnPage.setSumObject(purchaseVo);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }



    @ApiOperation(value = "获取可退货的采购单", notes = "获取可退货 销售单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @GetMapping(value = "/findCanRefundList")
    public Result findCanRefundList(PurchaseDto dto, HttpServletRequest request) {
        try {
            dto.setShipmentCode(UserUtil.getShipmentCompanyCode());
            // 根据仓库、入驻商、客户、已发数量>退货数量 获取销售单
            List<Purchase> PurchaseVo = purchaseService.findCanRefundList(dto);
            return Result.ok().data(PurchaseVo);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }



    @ApiOperation(value = "获取可退货 采购单明细", notes = "获取可退货 采购单明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @GetMapping(value = "/findCanRefundItemList")
    public Result findCanRefundItemList(PurchaseItemDto dto, HttpServletRequest request) {
        try {
            // 根据仓库、入驻商、客户、已发数量>退货数量 获取销售单
            List<PurchaseItemVO> purchaseItemVOList = purchaseService.findCanRefundItemList(dto);

            return Result.ok().data(purchaseItemVOList);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

}
